from django.shortcuts import  render, redirect
from django.http import JsonResponse, HttpResponse
from app01.forms.wiki import WikiModelForm
from app01.forms.project import FPY_rateModelForm, Yield_rateModelForm,Output_by2hourModelForm
from django.urls import reverse
from app01 import models
from django.views.decorators.csrf import csrf_exempt
def wiki(request, project_id):
    """ wiki的首页"""
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')

    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()

    return render(request, 'wiki.html', {'wiki_object': wiki_object})
def wiki_add(request, project_id):
    """ 添加wiki """
    if request.method == 'GET':
        form=WikiModelForm(request)

        return render(request, 'wiki_form.html',{'form':form})
    form = WikiModelForm(request,request.POST )
    if form.is_valid():
        if(form.instance.parent):
            form.instance.depth=form.instance.parent.depth+1
        else:
            form.instance.depth=1
        # 验证通过，写入数据库（密码要是密文）
        # instance = form.save，在数据库中新增一条数据，并将新增的这条数据赋值给instance
        form.instance.project=request.tracer.project
        form.save()
        url=reverse('wiki',kwargs={'project_id':project_id})
        return redirect(url)
    return render(request, 'wiki_form.html', {'form': form})
def wiki_catalog(request, project_id):
    """ wiki的目录 """
    data = models.Wiki.objects.filter(project_id=project_id).values("id", "title", "parent_id").order_by('depth','id')
    return JsonResponse({'status': True,'data':list(data)})
def wiki_edit(request, project_id, wiki_id):
    """ 编辑wiki """
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id ).first()
    if not wiki_object:
        url=reverse('wiki',kwargs={'project_id':project_id})
        return redirect(url)
    if request.method == 'GET':

        form = WikiModelForm(request,instance=wiki_object)
        return render(request, 'wiki_form.html', {'form': form})
    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        if(form.instance.parent):
            form.instance.depth=form.instance.parent.depth+1
        else:
            form.instance.depth=1
        # 验证通过，写入数据库（密码要是密文）
        # instance = form.save，在数据库中新增一条数据，并将新增的这条数据赋值给instance
        form.instance.project=request.tracer.project
        form.save()
        url=reverse('wiki',kwargs={'project_id':project_id})
        preview_url="{0}?wiki_id={1}".format(url,wiki_id)
        return redirect(preview_url)
    return render(request, 'wiki_form.html', {'form': form})
def wiki_delete(request, project_id, wiki_id):
    """ 删除wiki """
    models.Wiki.objects.filter(project_id=project_id,id=wiki_id).delete()
    url=reverse('wiki',kwargs={'project_id':project_id})
    return redirect(url)

import uuid
from django.conf import settings
import os
@csrf_exempt
def wiki_upload_img(request, project_id):
    """ markdown编辑器 上传图片 """
    print("收到图片了")
    image_object=request.FILES.get('editormd-image-file')
    # 获取图片后缀
    image_name=image_object.name
    image_ext=image_name.rsplit('.')[-1]
    # 将图片写入到指定目录\static\img\index\wiki_upload中
    image_name="{0}.{1}".format(uuid.uuid4().hex,image_ext)
    image_dir=os.path.join(settings.MEDIA_ROOT, 'wiki_upload')
    if not os.path.isdir(image_dir):
        os.makedirs(image_dir)
    image_path=os.path.join(image_dir, image_name)
    print(image_path)
    with open(image_path, 'wb') as f:
        for chunk in image_object.chunks():
            f.write(chunk)
    # 返回图片的 URL
    image_url = request.build_absolute_uri(f"/media/wiki_upload/{image_name}")
    print(image_url)
    result={
        "success": 1,
        "message": None,
        "url": image_url
    }
    return JsonResponse(result)
def fpy(request, project_id):
    if request.method == 'GET':
        form=FPY_rateModelForm(request)
        return render(request, 'fpy.html',{'form':form})
    else:
        form = FPY_rateModelForm(request,request.POST )
        if form.is_valid():
            form.instance.project=request.tracer.project
            form.instance.DRI=request.tracer.user
            print('got here and ok yet',request.tracer.project,request.tracer.user)
            #  获取用户领导，在ProjectDRI表内，包含每个醒目对应段的user-->leader
            project_dir_object=models.ProjectDRI.objects.filter(project=request.tracer.project,AOIuser=request.tracer.user).first()  # 获取当前用户在项目内对应AOIuser的project_dir对象
            print(project_dir_object)
            if project_dir_object:  # 如果存在project_dir_object对象，则获取其leader
                form.instance.DRI_Leader=project_dir_object.AOIuser_leader  #获取project_dir_object对象的leader
            else:
                form.instance.DRI_Leader=None


            form.save()
            url=reverse('wiki',kwargs={'project_id':project_id})
            return redirect(url)
        return render(request, 'fpy.html', {'form': form})
def yield_rate(request, project_id):
    if request.method == 'GET':
        form=Yield_rateModelForm(request)
        return render(request, 'yield_rate.html',{'form':form})
    else:
        pass
def output(request, project_id):
    if request.method == 'GET':
        form=Output_by2hourModelForm(request)
        return render(request, 'output.html',{'form':form})
    else:
        pass
